const viewModules = import.meta.glob('../views/**/*.vue')
const layoutModules = import.meta.glob('../layout/**/*.vue')

export const asyncRouterHandle = asyncRouter => {
  asyncRouter.forEach(item => {
    // console.log('component: ', item.component, item.component.split('/')[0])
    if (item.component && typeof item.component === 'string') {
      if (['views'].includes(item.component.split('/')[0])) {
        item.component = dynamicImport(viewModules, item.component)
      } else if (item.component.split('/')[0] === 'layout') {
        item.component = dynamicImport(layoutModules, item.component)
      }
    }
    if (item.children) {
      asyncRouterHandle(item.children)
    }
  })
}

function dynamicImport(dynamicViewsModules, component) {
  const keys = Object.keys(dynamicViewsModules)
  const matchKeys = keys.filter(key => {
    const k = key.replace('../', '')
    return k === component
  })
  const matchKey = matchKeys[0]

  return dynamicViewsModules[matchKey]
}
